package e2e

import (
	"testing"

	"github.com/lab-online/pkg/auth"
	"github.com/lab-online/pkg/e2e"
	"github.com/lab-online/pkg/logger"
	"github.com/lab-online/pkg/resp"
	"github.com/stretchr/testify/assert"
)

type updatePasswordReqBody struct {
	OldPassword string `json:"oldPassword"`
	NewPassword string `json:"newPassword"`
}

func (ctx *context) defineUpdatePasswordRequest(
	username string,
	role auth.Role,
	targetUsername string,
	body *updatePasswordReqBody,
) *e2e.Request {
	return &e2e.Request{
		Method: "PATCH",
		Path:   ctx.Prefix + "/v1/users/" + targetUsername + "/password",
		Body:   body,
		Header: map[string]string{"Authorization": ctx.GenBearerToken(username, role)},
	}
}

func (ctx *context) CaseUpdatePassword1() (string, func(*testing.T)) {
	ctx.utilsCreateUser("00240331", auth.RoleStudent, "12345678")
	request := ctx.defineUpdatePasswordRequest("00240331", auth.RoleStudent,
		"00240331", &updatePasswordReqBody{
			OldPassword: "12345678",
			NewPassword: "123456789",
		})
	return "更新本人密码,需要原密码", func(t *testing.T) {
		response := ctx.JSONRequest(request)

		assert.Equal(t, 200, response.Code)

		body := e2e.JSONBodyParser[resp.SuccessRespBody[any]](response)

		assert.Equal(t, 20104, body.Code)
		assert.Empty(t, body.Data)
	}
}

func (ctx *context) CaseUpdatePassword2() (string, func(*testing.T)) {
	ctx.utilsCreateUser("10240331", auth.RoleStudent, "12345678")
	request := ctx.defineUpdatePasswordRequest("10240331", auth.RoleStudent,
		"10240331", &updatePasswordReqBody{NewPassword: "123456789"})
	return "更新本人密码,原密码错误", func(t *testing.T) {
		response := ctx.JSONRequest(request)

		assert.Equal(t, 400, response.Code)

		body := e2e.JSONBodyParser[resp.SuccessRespBody[any]](response)

		assert.Equal(t, 40103, body.Code)
		assert.Empty(t, body.Data)
	}
}

func (ctx *context) CaseUpdatePassword5() (string, func(*testing.T)) {
	ctx.utilsCreateUser("05240331", auth.RoleAdmin, "12345678")
	ctx.utilsCreateUser("06240331", auth.RoleStudent, "12345678")
	request := ctx.defineUpdatePasswordRequest("05240331", auth.RoleAdmin,
		"06240331", &updatePasswordReqBody{NewPassword: "1234567890"})
	return "管理员更新低权限用户密码,无需原密码", func(t *testing.T) {
		response := ctx.JSONRequest(request)

		assert.Equal(t, 200, response.Code)
		defer func() {
			if t.Failed() {
				logger.Warn(response.Body.String())
			}
		}()

		body := e2e.JSONBodyParser[resp.SuccessRespBody[any]](response)

		assert.Equal(t, 20104, body.Code)
		assert.Empty(t, body.Data)
	}
}
